#include <engine/e_server_interface.h>
#include <game/mapitems.hpp>
#include <game/server/entities/character.hpp>
#include <game/server/player.hpp>
#include <game/server/gamecontext.hpp>
#include <engine/e_config.h>
#include "flagrace.hpp"
#include "ctf.hpp"

GAMECONTROLLER_FR::GAMECONTROLLER_FR()
{
	reach = 0;
	gametype = "ReachRACE";
	//game_flags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode
}
bool GAMECONTROLLER_FR::on_entity(int index, vec2 pos)
{
	if(GAMECONTROLLER::on_entity(index, pos))
		return true;
	
	int team = -1;
	if(index == ENTITY_FLAGSTAND_BLUE) team = 0;
		REACH *r = new REACH(pos);
	if(team == -1)
		return false;
	reach = r;
	dbg_msg("game", "Exists");
	return true;
}

REACH::REACH(vec2 _pos)
: ENTITY(NETOBJTYPE_FLAG) /*TODO: Flag display */
{
	// TODO: should this be done here?
	game.world.insert_entity(this);
	pos = _pos;
	reached = false;
}


void GAMECONTROLLER_FR::tick()
{
	GAMECONTROLLER::tick();
	do_player_score_wincheck(); // checks for winners, no teams version
	if(reach)
	{
	CHARACTER *close_characters[MAX_CLIENTS];
	int num = game.world.find_entities(reach->pos, 16.0f, (ENTITY**)close_characters, MAX_CLIENTS, NETOBJTYPE_CHARACTER);
			for(int i = 0; i < num; i++)
			{
				if(!close_characters[i]->alive || col_intersect_line(reach->pos, close_characters[i]->pos, NULL, NULL))
					continue;
				
					if(!reach->reached)
					{
						close_characters[i]->reset();
						close_characters[i]->player->score = 1;
						char buf[100];
						str_format(buf, sizeof(buf), "The point has been reached by %s", server_clientname(close_characters[i]->player->client_id));
						endround();
						game.send_chat(-1, -2, buf);
					}
					reach->reached = 0;
			}
	}

				
}

int GAMECONTROLLER_FR::on_character_death(class CHARACTER *victim, class PLAYER *killer, int weapon){}
